package com.linfeng.api.controller;


import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.linfeng.api.annotation.AdminCheck;
import com.linfeng.api.param.LoginParam;
import com.linfeng.api.redis.util.RedisUtils;
import com.linfeng.api.service.TrymallAdminService;
import com.linfeng.api.util.jwt.JwtToken;
import com.linfeng.common.constant.RedisKeyConstant;
import com.linfeng.common.constant.ShopConstants;
import com.linfeng.common.domain.TrymallAdmin;
import com.linfeng.common.exception.TrymallException;
import com.linfeng.common.response.ApiCode;
import com.linfeng.common.response.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 管理员 前端控制器
 * </p>
 *
 * @author linfeng
 * @since 2021-01-20
 */
@RestController
@RequestMapping("/user")
public class TrymallAdminController {


    @Autowired
    private TrymallAdminService adminService;
    @Autowired
    private RedisUtils redisUtils;

    @PostMapping("/login")
    public ApiResult login(@Validated @RequestBody LoginParam loginParam){
        TrymallAdmin trymallAdmin = adminService.getOne(Wrappers.<TrymallAdmin>lambdaQuery()
                .eq(TrymallAdmin::getUsername, loginParam.getUsername())
                .eq(TrymallAdmin::getPassword, SecureUtil.md5(loginParam.getPassword())), false);
        if(trymallAdmin == null){
            throw new TrymallException(ShopConstants.ADMIN_LOGIN_REFUSE);
        }
        String token =  JwtToken.makeToken(Long.parseLong(trymallAdmin.getId()));
        redisUtils.set(RedisKeyConstant.TOKEN + token, token, 6, TimeUnit.HOURS);
        return ApiResult.result(ApiCode.LOGIN_SUCCESS,token);
    }

    @AdminCheck
    @PostMapping("/logout")
    public ApiResult logout(HttpServletRequest request){
        String bearerToken = request.getHeader("Authorization");
        String[] tokens = bearerToken.split(" ");
        String token = tokens[1];
        redisUtils.del(RedisKeyConstant.TOKEN + token);
        return ApiResult.result(ApiCode.LOGOUT_SUCCESS);
    }
}

